
const yDb = require('../../model/yunshijie');
const FastStatistics = yDb.FastStatistics;
const FastStatisticsDay = yDb.FastStatisticsDay;
const NewStatistics = yDb.NewStatistics;
const moment = require('moment');
const excuteEvent = require('../../utils/events');
const _ = require('lodash');
const Promise = require('bluebird');
/**
 * 记录头条相关的访问的信息
 * @param par
 */
function recordNews(par) {

    let viewPercent = par.viewPercent, keepTime = par.keepTime, nid = par.nid;
    let date = moment().format('YYYY-MM-DD');
    let update = {
        $inc: {viewCount: 1},   //阅读数量加1
        $push: {}
    };
    if (viewPercent) {
        update['$push'].viewPercent = viewPercent
    }
    if (keepTime) {
        update['$push'].keepTime = keepTime
    }

    return NewStatistics.findOneAndUpdate({nid, date}, update, {upsert: true}).exec()
}

/**
 * 修改快讯统计信息,    并存在初始化数据的情况
 * @param par   查询条件
 */
function updateAndSaveFastStatics(par) {
    let ids = par._ids, map;
    return FastStatistics.find({
        fid: ids
    })
        .then((datas)=> {
            let i, updateArr = [], saveArr = [];
            map = _.keyBy(datas, (item)=> item.fid);

            for (i = 0; i < ids.length; i++) {
                if (map[ids[i]]) {
                    updateArr.push(ids[i])
                } else {
                    saveArr.push({
                        fid: ids[i],
                        viewCount: 1    //初始默认为读过， 所以加1
                    })
                }
            }
            return Promise.props({
                //  存储
                save: new Promise((resolve, reject)=> {
                    FastStatistics.create(saveArr, (err)=> {
                        if (err) {
                            return reject(err)
                        }
                        return resolve()
                    })
                }),
                //  修改
                update: FastStatistics.updateMany({fid: updateArr}, {$inc: {viewCount: 1}}).exec()
            })
        })
        .then(()=> {
            //发送事件记录信息
            excuteEvent.emit('record_fast_operate', {ids: ids}, 'viewCount');
            return map
        })
}

/**
 * 根据type 修改相应的地方
 * @param par
 * @param type
 */
function updateFastStatics(par, type) {

    let _ids = par._ids;
    excuteEvent.emit('record_fast_operate', {ids: _ids}, type);
    //修改统计数量
    return FastStatistics.update({fid: _ids}, FastStatistics.operateByType(type)).exec()
}

module.exports = {
    //  记录头条相关的访问信息
    recordNews: recordNews,
    //  修改并初始化快讯数据信息
    updateAndSaveFastStatics: updateAndSaveFastStatics,
    //  修改统计数量
    updateFastStatics: updateFastStatics
};